# -*- coding: utf-8 -*-
import json

import math
from pyquery import PyQuery

from datetime import datetime, timedelta

from chdtp.items import ChdtpItemData
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import build_sha1_order_id, md5, short_uuid
from zc_core.util.common import parse_time, parse_number, parse_int

from chdtp.matcher import match_sku_id, match_supplier_id


def parse_mro_catalog(response):
    cats = list()
    docs = PyQuery(response.text)
    datas = docs('.yiji').children()
    for data in datas.items():
        cat1 = data.children('a:first-child')
        cat1_name = cat1.attr('title')
        id_text = cat1.attr('onclick')
        cat1_id = match_catalog_id(id_text, cat1_name)
        cats.append(build_catalog(cat1_id, cat1_name, 1))

        cat1_child = cat1.siblings().children()
        for cat2_li in cat1_child.items():
            cat2 = cat2_li.children('a:first-child')
            cat2_name = cat2.attr('title')
            cat2_id = match_catalog_id(cat2.attr('onclick'), cat2_name)
            cats.append(build_catalog(cat2_id, cat2_name, 2, cat1_id))

            cat2_child = cat2_li('.aa a')
            for cat3 in cat2_child.items():
                cat3_name = cat3.attr('title')
                cat3_id = match_catalog_id(cat3.attr('onclick'), cat3_name)
                cats.append(build_catalog(cat3_id, cat3_name, 3, cat2_id))

    return cats


def parse_office_catalog(response):
    cats = list()
    docs = PyQuery(response.text)
    rows = docs('.yiji').children()
    for row in rows.items():
        cat1 = row.children('div:first-child')
        cat1_name = cat1.text()
        id_text = cat1.attr('onclick')
        cat1_id = match_catalog_id(id_text, cat1_name)
        cats.append(build_catalog(cat1_id, cat1_name, 1))

        cat1_child = cat1.siblings().children()
        for cat2_li in cat1_child.items():
            cat2 = cat2_li.children('a:first-child')
            cat2_name = cat2.text()
            cat2_id = match_catalog_id(cat2.attr('onclick'), cat2_name)
            cats.append(build_catalog(cat2_id, cat2_name, 2, cat1_id))

            cat2_child = cat2_li('.aa a')
            for cat3 in cat2_child.items():
                cat3_name = cat3.text()
                cat3_id = match_catalog_id(cat3.attr('onclick'), cat3_name)
                cats.append(build_catalog(cat3_id, cat3_name, 3, cat2_id))

    return cats


def build_catalog(id, name, level, parent_id=None):
    entity = Catalog()

    entity['catalogId'] = id
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_supplier(response):
    batch_no = response.meta.get('batchNo')
    brand_list = list()
    docs = PyQuery(response.text)
    suppliers = docs('ul#id_displayGys li a')
    for row in suppliers.items():
        sp_name = row.attr('title')
        if sp_name and sp_name.strip():
            sp = Supplier()
            sp['id'] = md5(sp_name)
            sp['name'] = sp_name.strip()
            sp['batchNo'] = batch_no
            brand_list.append(sp)

    return brand_list


def parse_brand(response):
    batch_no = response.meta.get('batchNo')
    brand_list = list()
    docs = PyQuery(response.text)
    brands = docs('ul#id_displayPP li a')
    for row in brands.items():
        br_name = row.attr('title')
        if br_name and br_name.strip():
            brand = Brand()
            brand['id'] = md5(br_name)
            brand['name'] = br_name.strip()
            brand['batchNo'] = batch_no
            brand_list.append(brand)

    return brand_list


def match_catalog_id(id_text, name):
    if id_text:
        id_str = id_text.split(',')[1]
        if id_str and "'" in id_str:
            return id_str[1:-1]
    return md5(name)


def parse_total_page(response, page_size):
    docs = PyQuery(response.text)
    total_count = docs("input#Totalcount")
    if total_count and total_count.attr('value'):
        total_page = math.ceil(int(total_count.attr('value')) / page_size)
        return total_page

    return 0


def parse_sku_list(response):
    meta = response.meta
    catalog3_id = meta.get('catalog3Id')
    docs = PyQuery(response.text)
    skus = docs('.product_list .product_item')
    sku_list = list()
    help = CatalogHelper()
    if skus:
        meta = response.meta
        batch_no = meta.get('batchNo')
        for sku_el in skus.items():
            sku = Sku()
            sku['catalog3Id'] = catalog3_id
            help.fill(sku)
            sku['batchNo'] = batch_no
            sku_id = match_sku_id(sku_el('.item_name a').attr('href'))
            if not sku_id:
                sku_id = sku_el('div.item_price').attr('id')
            sku['skuName'] = sku_el('.item_name').text()
            sku['skuId'] = sku_id
            supplier = sku_el('.item_store a')
            sku['supplierId'] = md5(supplier.text().strip())
            sku['supplierName'] = supplier.text().strip()
            sku_list.append(sku)

    return sku_list


def parse_item_data(response):
    jpy = PyQuery(response.text)

    meta = response.meta
    batch_no = meta.get('batchNo')
    link_id = meta.get('linkId')
    sp_id = meta.get('supplierId')
    sp_name = meta.get('supplierName')

    sku_id = jpy('div.product_top_c div.name div.summary-price .dt:contains("商品编码：") + div.dd[id]')
    brand_name = jpy('div.pro_info_list div.summary-price .dt:contains("牌：") + div.dd').text().strip()
    brand_id = md5(brand_name)
    sku_img = jpy('div#spec-n1 img').attr('src')
    sku_name = jpy("div.name h2").text().strip()
    unit = jpy("div.choose_amount div.store-prompt").text().strip()
    bar_code = jpy('input#barcode').val().strip()
    catalog3_id = jpy('input#flbh').val().strip()
    material_code = jpy('input#smeifid').val().strip()
    sp_sku = jpy('input#spsku').val().strip()

    item = ChdtpItemData()
    item['batchNo'] = batch_no
    item['skuId'] = sku_id.text().strip()
    item['linkId'] = link_id
    item['skuName'] = sku_name
    item['spuId'] = bar_code
    item['barCode'] = bar_code
    item['skuImg'] = sku_img
    item['brandId'] = brand_id
    item['brandName'] = brand_name
    item['supplierId'] = sp_id
    item['supplierName'] = sp_name
    item['catalog3Id'] = catalog3_id
    item['materialCode'] = material_code
    item['unit'] = unit
    if sp_sku:
        item['supplierSkuId'] = sp_sku
        plat_code = None
        if sp_name and '得力' in sp_name:
            plat_code = 'deli'
        item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku)

    item['genTime'] = datetime.utcnow()
    return item


def parse_item_price(response):
    data = json.loads(response.text)
    if data and data.get('xsjg', ''):
        item = ItemDataSupply()
        meta = response.meta
        item['skuId'] = meta.get('skuId')
        item['batchNo'] = meta.get('batchNo')
        item['salePrice'] = parse_number(data.get('xsjg'))
        if data.get('scjg', ''):
            item['originPrice'] = parse_number(data.get('scjg'))
        else:
            item['originPrice'] = parse_number(data.get('xsjg'))

        return item


def parse_item_count(response):
    data = json.loads(response.text)
    if data and data.get('spxxxl'):
        item = ItemDataSupply()
        meta = response.meta
        item['skuId'] = meta.get('skuId')
        item['batchNo'] = meta.get('batchNo')
        item['soldCount'] = parse_int(data.get('spxxxl'))
        return item


def split_price(leftPrice, rightPrice):
    mean = leftPrice + math.floor((rightPrice - leftPrice) / 2)
    if rightPrice - leftPrice == 1:
        return [[leftPrice, leftPrice], [rightPrice, rightPrice]]
    elif leftPrice != rightPrice:
        return [[leftPrice, mean], [mean, rightPrice]]
    else:
        return []
